package com.boot.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.boot.entity.User;
import com.boot.service.UserService;
import com.boot.service.ex.ServiceException;
import com.boot.service.ex.TokenNotExitException;
import com.boot.service.ex.WithoutToken;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //执行认证
        if(StrUtil.isBlank(token)){
            throw new WithoutToken("token不能为空");
        }
        //获取 token中的userId
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException e) {
            throw new TokenNotExitException("token验证失败");
        }
        User user = userService.getById(userId);
        if(user == null){
            throw new ServiceException("用户不存在！");
        }
        //用户验证签名 token
        JWTVerifier jwt = JWT.require(Algorithm.HMAC256("shuchong")).build();
        try {
            jwt.verify(token);
        } catch (JWTVerificationException e) {
            throw new TokenNotExitException("token验证失败");
        }
        return true;
    }
}
